/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.uc.labs.MobilePrinting.Fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.NoRouteToHostException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Scanner;

import static edu.uc.labs.MobilePrinting.Configurator.*;

/**
 * 
 * This class sends data to the Server and receives an XML formated list of
 * Printers
 * 
 * @param server
 *            the IPAddress or DNS name of the server
 * @param ipAddress
 *            the IPAddress to send to the server
 */
public class XMLFetcher {

	private String input = "";
	private String resource = "/GetPrinters?ip=";
	private String os = "&os=";
	private String url, server, ip;
	private URL u;
	private URLConnection conn;

	public XMLFetcher(String iServer, String iAddress, String osName)
			throws MalformedURLException, IOException, NoRouteToHostException {
		server = iServer;
		ip = iAddress;
		os += URLEncoder.encode(osName,"UTF-8") ;
		connect();
	}

	public String getResponse() {
		return input;
	}

	public boolean isConnected() {
		return true;
	}

	public void connect() throws IOException, ConnectException {
		buildURL();
		LOGGER.debug("The URL to send: " + u.toString());
		conn = u.openConnection();
		InputStream instream = conn.getInputStream();
		Scanner in = new Scanner(instream);
		while (in.hasNextLine()) {
			input += in.nextLine() + "\n";
		}

	}

	public void buildURL() throws MalformedURLException {
		// Build the URL
		url = "http://" + server + resource + ip + os;
		u = new URL(url);
	}

	public void setIP(String newIP) {
		ip = newIP;
	}

}
